package com.heima.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //设置值
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }
    // 获取值
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
    //设置值并设置过期时间（确保有效期内只有一个值）
    public boolean setWithExpiration(String key, String value, long timeout) {
       return stringRedisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
    }
    // 删除键
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }
    // 检查键是否存在
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }
    
    // 设置值并设置过期时间（天）
    public void setWithExpirationDays(String key, String value, long days) {
        stringRedisTemplate.opsForValue().set(key, value, days, TimeUnit.DAYS);
    }
}
